package com.mugui.spring.net.websocket;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mugui.spring.base.ManagerInterface;
import com.mugui.spring.net.auto.AutoManager;
import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.net.task.TaskManager;

@Component
@AutoManager
public class WebSocketSessionManager implements ManagerInterface<String, Session> {

	private static Map<String, Session> map = null;

	public void init() {
		if (map == null) {
			synchronized (WebSocketSessionManager.class) {
				if (map == null)
					map = new ConcurrentHashMap<>();
			}
		}
	}

	@Autowired
	private WebSocketManager webSocketManager;
	@Autowired
	private WebSocketPingTask webSocketPingTask;

	public boolean init(Object name) {
		System.out.println(WebSocketSessionManager.class.getName() + "初始化");
		init();
		clear();
		if (!webSocketManager.isOpenWebSocket()) {
			return true;
		}
		webSocketPingTask.init();
		TaskManager.getTaskManager().add(webSocketPingTask);
		webSocketTask.init();
		TaskManager.getTaskManager().add(webSocketTask);
		return true;
	}

	@Override
	public Session get(String name) {
		init();
		return map.get(name);
	}

	@Override
	public Session del(String name) {
		init();
		Session remove = map.remove(name);
		if (remove != null) {
			Collection<ConcurrentHashMap<String, ConcurrentHashMap<Session, NetBag>>> values = webSocketTask.values();
			for (ConcurrentHashMap<String, ConcurrentHashMap<Session, NetBag>> concurrentHashMap : values) {
				for (ConcurrentHashMap<Session, NetBag> concurrentHashMap2 : concurrentHashMap.values()) {
					concurrentHashMap2.remove(remove);
				}
			}
		}
		return remove;
	}

	@Autowired
	private WebSocketTask webSocketTask;

	public void sub(Session session, NetBag bag) {
		if (!webSocketManager.isOpenWebSocket()) {
			return;
		}
		webSocketTask.sub(session, bag);
	}

	public void unsub(Session session, NetBag bag) {
		if (!webSocketManager.isOpenWebSocket()) {
			return;
		}
		webSocketTask.unsub(session, bag);
	}

	@Override
	public boolean add(String name, Session object) {
		init();
		map.put(name, (Session) object);
		return true;
	}

	@Override
	public boolean clear() {
		init();
		webSocketTask.clear();
		map.clear();
		return true;
	}

	@Override
	public boolean is(String name) {
		return map.containsKey(name);
	}

	public Collection<Session> values() {
		return map.values();
	}

	@Override
	public boolean isInit() {
		return false;
	}

}
